package com.jade.journal.appender;

import com.jade.framework.base.context.ApplicationContextUtils;
import com.jade.journal.AbstractAppender;
import com.jade.journal.JournalEntity;
import com.jade.journal.JournalEntityManager;
import com.jade.journal.JournalEvent;
import com.jade.journal.desc.AppenderDesc;
import com.jade.journal.desc.JournalDesc;

/**
 * 采用数据库方式记录的日志。
 *
 * @author sky
 * @version 1.0 14-9-23 下午1:38
 */
public class DatabaseAppender extends AbstractAppender
{
    public static final String TYPE = "database";

    protected JournalEntityManager journalEntityManager;

    public void setJournalEntityManager(JournalEntityManager journalEntityManager)
    {
        this.journalEntityManager = journalEntityManager;
    }

    protected JournalEntityManager getEntityManager()
    {
        if (journalEntityManager == null) {
            journalEntityManager = ApplicationContextUtils.getBean("system_journalEntityManager");
        }
        return journalEntityManager;
    }

    public DatabaseAppender(JournalDesc desc, AppenderDesc appenderDesc)
    {
        super(TYPE, desc, appenderDesc);
    }

    public void append(JournalEvent... events)
    {
        for (JournalEvent event : events) {
            Object item = event.getItem();
            if (item instanceof JournalEntity) {
                getEntityManager().addEntity((JournalEntity)item);
            }
            else {
                log.error("Don't support event entity:" + item.getClass().getSimpleName());
            }
        }
    }
}
